package com.example.agingaid;

import java.util.Timer;
import java.util.TimerTask;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.telephony.SmsManager;

public class MainScreen extends Activity implements View.OnClickListener{

	Button alertButton,	inactivityButton, locationalButton;
	String prefName, prefNum, provider, homeLat, homeLong, radius, inactiveMinText;
	ImageButton panicButton;
	TextView contactName, contactNumber, latText, motionText;
	SharedPreferences prefs;
	SmsManager smsManager;
	long minNum;
	LocationManager locationManager;
	Location location;
	Timer timer;
	TimerTask smsTimerTask;
	private static String PROXIMITY_ALERT = "com.example.agingaid.gps.ProximityIntentReciever";
	boolean locationStatus, activityStatus, messageSent = false;
	boolean timerStatus, movement;

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.main_screen);

        switch (this.getResources().getConfiguration().orientation)
        {
        	case Configuration.ORIENTATION_PORTRAIT:
        		// Do something here
        		break;
        	case Configuration.ORIENTATION_LANDSCAPE:
        		Intent i = new Intent(MainScreen.this, RotateCode.class);
				startActivity(i);
        		break;
        default:
        }
        
        latText = (TextView)findViewById(R.id.textView4);
        contactName = (TextView)findViewById(R.id.textView2);
        contactNumber = (TextView)findViewById(R.id.textView3);
        motionText = (TextView)findViewById(R.id.textView6);
        
        smsManager = SmsManager.getDefault();
        
        locationalButton=(Button)findViewById(R.id.button1);
        inactivityButton=(Button)findViewById(R.id.button2);
        panicButton=(ImageButton)findViewById(R.id.button4);
        
        prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        
    	prefName = prefs.getString("primary_name","Nothing has been entered");
    	contactName.setText(prefName);
    	
    	prefNum = prefs.getString("primary_number","Nothing has been entered");
    	contactNumber.setText(prefNum);
        
        locationStatus = prefs.getBoolean("locational_pref", true);
        
        if(locationStatus == true){
        	locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
            provider = LocationManager.GPS_PROVIDER;
            location = locationManager.getLastKnownLocation(provider);
            updateWithNewLocation(location);
            locationManager.requestLocationUpdates(provider, 5000, 5, locationListener);
            
            IntentFilter filter = new IntentFilter(PROXIMITY_ALERT);
            registerReceiver(new ProximityIntentReciever(), filter);
            setProximityAlert();
        }
                
        inactiveMinText = prefs.getString("inactivity_length", "0");
        
        minNum = Long.valueOf(inactiveMinText);
        
        activityStatus = prefs.getBoolean("inactivity_pref", true);
        
        if(activityStatus == true){
        	SensorManager sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
        	int sensorType = Sensor.TYPE_ACCELEROMETER;
        	sensorManager.registerListener(sensorListener, sensorManager.getDefaultSensor(sensorType), SensorManager.SENSOR_DELAY_NORMAL);
        }
        		       		
        panicButton.setOnClickListener(new Button.OnClickListener(){
	    public void onClick(View arg0) {
	    	 // TODO Auto-generated method stub
		     String smsNumber = contactNumber.getText().toString();
		     String smsText = "ALERT! The Panic Button has been pressed in Aging Aid. Please Attempt to contact the user.";
		     smsManager.sendTextMessage(smsNumber, null, smsText, null, null);
	    }});      
        
        locationalButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(MainScreen.this, LocationalScreen.class);
				startActivity(i);
			}
		});
        
        inactivityButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(MainScreen.this, InactivityScreen.class);
				startActivity(i);
			}
		});
    }
	
    	LocationListener locationListener = new LocationListener(){
    	
		public void onLocationChanged(Location location) {
			updateWithNewLocation(location);
		}
		public void onProviderDisabled(String provider) {}
		public void onProviderEnabled(String provider) {}
		public void onStatusChanged(String provider, int status, Bundle extras) {		}
    };
    
    public void updateWithNewLocation(Location location){  	
    	if(location != null){
    		double lat = location.getLatitude();
    		double lng = location.getLongitude();
    		    		
    		latText.setText("Lat: " + lat + "\nLong: " + lng);
    	}
    }
    
    private void setProximityAlert(){
    	String locService = Context.LOCATION_SERVICE;
    	LocationManager locManager;
    	locManager = (LocationManager)getSystemService(locService);
    	
    	homeLat = prefs.getString("home_lat_pref","0");
    	homeLong = prefs.getString("home_long_pref","0");
    	radius = prefs.getString("fence_range","0");
    	
    	double lat = Double.valueOf(homeLat);
    	double lng = Double.valueOf(homeLong);
    	float rad = Float.valueOf(radius);
    	long expiration = -1;
    	
    	Intent intent = new Intent(PROXIMITY_ALERT);
    	
    	PendingIntent proximityIntent = PendingIntent.getBroadcast(this, -1, intent, 0);
    	locManager.addProximityAlert(lat, lng, rad, expiration, proximityIntent);
    }
        
		SensorEventListener sensorListener = new SensorEventListener(){
   	
		public void onSensorChanged(SensorEvent event) {
				updateWithNewSensorVal(event);
			}

		public void onAccuracyChanged(Sensor sensor, int accuracy) {}
	    };
	    
	    private void updateWithNewSensorVal(SensorEvent sensorVal){
	    	motionText.setText("X: " + sensorVal.values[0] + "\nY: " + sensorVal.values[1] + "\nZ: " + sensorVal.values[2]);
	    		        	    	
	    	double accMag = (sensorVal.values[0]*sensorVal.values[0]) + (sensorVal.values[1]*sensorVal.values[1]) + (sensorVal.values[2]*sensorVal.values[2]);
			double mag = Math.sqrt(accMag);
			
			if(mag < 8.8 || mag > 10.8){
				if(timerStatus == true){
					timer.cancel();
					smsTimerTask.cancel();
				}
				movement = true;
				timerStatus = false;
				System.out.println("Phone is moving, timer cancelled");
			}	
			
			else{
				movement = false;
				System.out.println("Phone is NOT moving");
				if(timerStatus == false){				
					System.out.println("Timer Started");
					timer = new Timer();
					smsTimerTask = new TimerTask() {
							@Override
							public void run() {
								if(messageSent == false && movement == false){
								    String smsNumber = contactNumber.getText().toString();
								    String smsText = "ALERT! The phone in Aging Aid has been not been moved for the set time.";
								    smsManager.sendTextMessage(smsNumber, null, smsText, null, null);
								    messageSent = true;
								    System.out.println("TEXT MESSAGE SENT");
								}	
							}
						};
					timer.schedule(smsTimerTask, (minNum*1000*60));
					timerStatus = true;
				}
				}
	    }
	    
		@Override
		public boolean onCreateOptionsMenu(Menu menu) 
		{	MenuInflater inflater = getMenuInflater();
		    inflater.inflate(R.menu.option_menu, menu);
		    return true;
		}
		
		public void goHome(){
			Intent i = new Intent(this, MainScreen.class);
			startActivity(i);
		}
		
		public void showSettings(){
			Intent i = new Intent(this, Settings.class);
			startActivity(i);
		}
		
		@Override
		public boolean onOptionsItemSelected(MenuItem item) {
		    // Handle item selection
		    switch (item.getItemId()) {
		        case R.id.menu_home:
		            goHome();
		            return true;
		        case R.id.menu_settings:
		            showSettings();
		            return true;
		        default:
		            return super.onOptionsItemSelected(item);
		    }
		}
		
		public void onClick(View v) {
			// TODO Auto-generated method stub
		}
		
		@Override
		public void onBackPressed() {
		   Intent setIntent = new Intent(Intent.ACTION_MAIN);
		   setIntent.addCategory(Intent.CATEGORY_HOME);
		   setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		   startActivity(setIntent);
		}
}
